/**
 * 易驰护运 - OrderInTransitDetail
 * http://menger.me
 * @桓桓
 */

'use strict';

import React from 'react';
import {
    View,
    Text,
    ScrollView, 
    StyleSheet,
    TouchableOpacity,
} from 'react-native';
import {
    LargePicture,
    ListHeaderLoading,
} from '../../components';
import {inject, observer} from 'mobx-react';
import Webview from 'react-native-webview';

const injectedJavascript = `(function() {
    window.postMessage = function(data) {
      window.ReactNativeWebView.postMessage(data);
    };
  })()`;

@inject('loginStore')
@observer
export default class OrderInTransitDetail extends React.Component {
    constructor(props) {
        super(props);
        this.params = this.props.navigation.state.params;
        this.state = {
            loading: true,
            isRefreshing: false,
            orderType: 0,
            dataSource: [],
            timeDataSource: [],
            loading_img_status: '',
            discharge_img_status: '',
            addressText: '',
            uri: '',
            x1: 1,
            y1: 1,
            x2: 1,
            y2: 1,
            x3: 1,
            y3: 1,
            x4: 1,
            y4: 1,
            x5: 1,
            y5: 1,
            x6: 1,
            y6: 1,
            x7: 1,
            y7: 1,
            x8: 1,
            y8: 1,
        }
    }

    componentDidMount () {
        this.request();
    }

    request = async () => {
        await this.requestData();
        await this.requestTimeCardData();
        await this.requestWebData();
    }

    _onRefresh = async () => {
        this.setState({isRefreshing: true});
        await this.requestData();
        await this.requestTimeCardData();
        await this.requestWebData();
        setTimeout(() => this.setState({isRefreshing: false}), 500);
    };

    // 请求页面信息
    requestData = async () => {
        let {item} = this.params;
        let url = ServicesApi.VEHICLE_ORDER_INFO;
        let data = {
            id: item.id,
        };
        const result = await Services.post(url, data);
        if (result.code === StatusCode.SUCCESS_CODE) {
            this.setState({
                dataSource: result.data,
                orderType: result.data.vehicle_order_status,
                loading: false,
            });
        }
    }

    // 请求时间轴数据
    requestTimeCardData = async () => {
        let {item} = this.params;
        let url = ServicesApi.VEHICLE_ORDER_LOG;
        let data = {
            vehicle_order_id: item.id,
        };
        const result = await Services.post(url, data);
        if (result.code === StatusCode.SUCCESS_CODE) {
            this.setState({
                timeDataSource: result.data.dataList,
                loading_img_status: result.data.status.loading_img_status,
                discharge_img_status: result.data.status.discharge_img_status,
            });
            result.data.dataList.map((_item, _index) => {
                switch (_item.vehicle_order_log_status) {
                    case 1:
                        this.setState({
                            x1: Number(_item.warp) || 1,
                            y1: Number(_item.weft) || 1,
                        })
                        break;
                    case 2:
                        this.setState({
                            x2: Number(_item.warp) || 1,
                            y2: Number(_item.weft) || 1,
                        })
                        break;
                    case 3:
                        this.setState({
                            x3: Number(_item.warp) || 1,
                            y3: Number(_item.weft) || 1,
                        })
                        break;
                    case 4:
                        this.setState({
                            x4: Number(_item.warp) || 1,
                            y4: Number(_item.weft) || 1,
                        })
                        break;
                    case 5:
                        this.setState({
                            x5: Number(_item.warp) || 1,
                            y5: Number(_item.weft) || 1,
                        })
                        break;
                    case 6:
                        this.setState({
                            x6: Number(_item.warp) || 1,
                            y6: Number(_item.weft) || 1,
                        })
                        break;
                    case 7:
                        this.setState({
                            x7: Number(_item.warp) || 1,
                            y7: Number(_item.weft) || 1,
                        })
                        break;
                    case 8:
                        this.setState({
                            x8: Number(_item.warp) || 1,
                            y8: Number(_item.weft) || 1,
                        })
                        break;
                    default:
                        break;
                }
                
            })
        }
    }

    // 请求web的地图
    requestWebData = async () => {
        let {orderType, x1, y1, x2, y2, x3, y3, x4, y4, x5, y5, x6, y6, x7, y7, x8, y8} = this.state;
        let url = ServicesApi.VEHICLE_DRIVER_MAP;
        let data = {
            status: orderType,
            x1: x1,
            y1: y1,
            x2: x2,
            y2: y2,
            x3: x3,
            y3: y3,
            x4: x4,
            y4: y4,
            x5: x5,
            y5: y5,
            x6: x6,
            y6: y6,
            x7: x7,
            y7: y7,
            x8: x8,
            y8: y8,
        };
        const result = await Services.post(url, data);
        if (result.code === StatusCode.SUCCESS_CODE) {
            this.setState({
                uri: result.data.url
            })
        }
    }

    imageListView = (data) => {
        let imageDataSource = data.weigh_img.split('|');
        let contain = Array.isArray(imageDataSource) && imageDataSource.map((item, index) => {
            return (
                <LargePicture
                    key={index}
                    resizeMode={'cover'}
                    style={styles.statusImg}
                    imageStyle={styles.statusImg}
                    source={{uri: item}}
                />
            ) 
        })
        return (
            <ScrollView 
                style={styles.statusImgBox} 
                horizontal={true}
                showsHorizontalScrollIndicator={false}
            >
                {contain}
            </ScrollView>
        )
    }

    cardListView = (data) => {
        let contain = data.map((item, index) => {
            return (
                item.is_complete == 0 
                ?
                <View key={index} style={[styles.cardTimeLine, index == 0 && {marginTop: 0}]}>
                    <Text style={styles.cardTimeLineDay} numberOfLines={1}>暂未到达</Text>
                    <View style={styles.cardTimeLineImgBox}>
                        <ImageView
                            resizeMode={'contain'}
                            style={styles.cardTimeLineImg}
                            source={Images.icon_time_card_logo3}
                        />
                    </View>
                    <ImageView
                        resizeMode={'contain'}
                        style={styles.cardTimeLineRightArrow}
                    />
                    <View style={styles.cardTimeLineRight}>
                        <Text style={styles.cardTimeLineRightText} numberOfLines={1}>{item.vehicle_order_log_status_text}</Text>
                    </View>
                </View>
                :
                <TouchableOpacity 
                    key={index} 
                    style={[styles.cardTimeLine, index == 0 && {marginTop: 0}]} 
                    onPress={() => {
                        this.setState({orderType: item.vehicle_order_log_status}, () => this.requestWebData())
                    }}
                >
                    <Text style={styles.cardTimeLineDayCur} numberOfLines={2}>{item.update_time}</Text>
                    <View style={styles.cardTimeLineImgBoxCur}>
                        <ImageView
                            resizeMode={'contain'}
                            style={styles.cardTimeLineImgCur}
                            source={Images.icon_time_card_logo1}
                        />
                    </View>
                    <ImageView
                        resizeMode={'contain'}
                        style={styles.cardTimeLineRightArrow}
                        source={Images.icon_time_card_logo2}
                    />
                    <View style={[styles.cardTimeLineRightCur]}>
                        <Text style={styles.cardTimeLineRightTextCur} numberOfLines={1}>{item.vehicle_order_log_status_text}</Text>
                        {
                            item.weigh != null &&
                            <View>
                                {this.imageListView(item)}
                                <View style={styles.smallStatusTextBox}>
                                    <Text style={styles.statusText} numberOfLines={1}>{item.is_pass_text}</Text>
                                </View>
                                <Text style={styles.statusWeigh}>装货吨数:<Text style={{color: '#FC6911'}}>{item.weigh}</Text>吨</Text>
                                {item.reasons && <Text style={styles.reasons}>原因：{item.reasons}</Text>}
                            </View>
                        }
                    </View>
                </TouchableOpacity>
            )
        })
        return (
            <View style={styles.cardTime}>
                <View style={styles.line}/>
                {contain}
            </View>
        )
    }

    render() {
        let pageTitle = this.params.pageTitle || '司机订单详情';
        let {loading, orderType, timeDataSource, discharge_img_status, uri} = this.state;
        let icon_marker = '';
        switch (orderType) {
            case 1:
                icon_marker = Images.icon_marker1
                break;
            case 2:
                icon_marker = Images.icon_marker2
                break;
            case 3:
                icon_marker = Images.icon_marker3
                break;
            case 4:
                icon_marker = Images.icon_marker4
                break;
            case 5:
                icon_marker = Images.icon_marker5
                break;
            case 6:
                icon_marker = Images.icon_marker6
                break;
            case 7:
                icon_marker = Images.icon_marker7
                break;
            case 8:
                icon_marker = Images.icon_marker8
                break;
            default:
                break;
        }
        return (
            <PageContainer loading={loading} style={styles.container}>
                <NavigationBar 
                    title={pageTitle} 
                    style={styles.navigationBar}
                />
                <View style={styles.headerPadding}/>
                <View style={styles.webContainer}>
                    <Webview
                        source={{uri}}
                        onLoadEnd={this.onLoadEnd}
                        startInLoadingState={false}
                        style={styles.webContainer}
                        injectedJavaScript={injectedJavascript} // 注入js代码
                        onMessage={(event) => this.onMessage(event)}
                    />
                </View>
                <View style={styles.addressBox}>
                    <ImageView
                        resizeMode={'contain'}
                        style={styles.addressBoxImg}
                        source={icon_marker}
                    />
                    <Text style={styles.addressBoxText}>{this.state.addressText}</Text>
                </View>
                <ScrollView
                    style={styles.content}
                    refreshControl={<ListHeaderLoading onRefresh={this._onRefresh} refreshing={this.state.isRefreshing}/>}
                >
                    <View style={styles.card}>
                        <View style={styles.cardHeader}>
                            <View style={styles.cardHeaderBall}>
                                <View style={styles.cardHeaderBallCenter}/>
                            </View>
                            <Text style={styles.cardHeaderText} numberOfLines={1}>时间轴</Text>
                        </View>
                        {this.cardListView(timeDataSource)}
                    </View>
                </ScrollView>
            </PageContainer>
        );
    }

    onMessage = (event) => {
        console.log(event.nativeEvent.data);
        this.setState({addressText: event.nativeEvent.data})
    }
}

const DominantColor = '#00BFCC';
const contentWidth = Predefine.screenWidth - 20;
const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    navigationBar: {
        zIndex: 10,
        position: 'absolute',
    },
    headerPadding: {
        height: NAV_BAR_HEIGHT,
    },
    rightAction: {
        width: 20,
        height: 20,
    },
    content: {
        
    },
    navItemStyle: {
        marginTop: 10,
    },

    contentItemView: {
        minHeight: 100,
        marginBottom: 10,
        paddingVertical: 15,
        paddingHorizontal: 15,
        backgroundColor: '#fff',
    },
    contentSmallItemView: {
        paddingHorizontal: 10,
    },
    contentItemBgView: {
        top: 0,
        left: 0,
        height: 100,
        position: 'absolute',
        width: Predefine.screenWidth,
        backgroundColor: Predefine.themeColor,
    },
    detailAddressView: {
        width: contentWidth,
        paddingVertical: 15,
        paddingHorizontal: 15,
        // height: contentWidth * 0.45,
    },
    addressInfoStyle: {
        marginVertical: 0,
    },
    addressInfoSeparator: {
        marginVertical: 5,
        backgroundColor: Predefine.themeColor,
    },
    // 顶部发片底部的信息（货物名称，货物类型，货物重量）
    cargoInfoCardContent: {
        marginTop: 10,
    },
    cargoInfoCardItemView: {
        flex: 2,
    },
    cargoInfoCardItemViewCenter: {
        flex: 3,
    },
    cargoInfoCardItemValue: {
        fontSize: 14,
        fontWeight: '700',
        textAlign: 'center',
        color: Predefine.themeColor,
    },
    cargoInfoCardItemTitleView: {
        marginTop: 5,
    },
    cargoInfoCardItemTitle: {
        fontSize: 12,
        color: '#666',
    },
    cargoInfoCardItemTitleIcon: {
        width: 12,
        height: 12,
        marginRight: 3,
    },
    cargoInfoCardSeparator: {
        width: 1,
        height: 25,
        backgroundColor: Predefine.themeColor,
    },
    orderId: {
        marginTop: 10,
        fontSize: 12,
        color: '#333',
    },

    card: {
        marginBottom: 10,
        backgroundColor: '#fff',
        paddingHorizontal: 15,
        paddingBottom: 10,
    },
    cardHeader: {
        flexDirection: 'row',
        alignItems: 'center',
        height: 40,
    },
    cardHeaderBox: {
        borderTopWidth: Predefine.minPixel,
        borderTopColor: '#F0F0F0',
    },
    cardHeaderIcon: {
        marginLeft: 15,
        marginTop: 10,
    },
    cardHeaderBall: {
        width: 12,
        height: 12,
        borderRadius: 6,
        backgroundColor: DominantColor,
        marginRight: 6,
        alignItems: 'center',
        justifyContent: 'center',
    },
    cardHeaderBallCenter: {
        height: 6,
        width: 6,
        borderRadius: 3,
        backgroundColor: '#fff',
    },
    cardHeaderText: {
        color: '#333',
        fontSize: 15,
        fontWeight: 'bold',
    },

    cardLineBox: {
        flex: 1,
    },
    cardHeaderBoxRight: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-around',
    },
    cardLine: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        height: 30,
    },
    cardLineLeft: {
        color: '#333',
        fontSize: 14,
    },
    cardLineRight: {
        color: '#666',
        fontSize: 14,
        flex: 1,
        textAlign: 'right',
    },

    addressBox: {
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: '#fff',
        marginBottom: 10,
        paddingHorizontal: 15,
        paddingVertical: 10,
    },
    addressBoxImg: {
        width: 32,
        height: 32,
        marginRight: 10,
    },
    addressBoxText: {
        fontSize: 15,
        color: '#333',
        flex: 1,
        lineHeight: 20,
    },

    // 时间轴样式
    cardTime: {
        overflow: 'hidden',
    },
    line: {
        width: 1,
        backgroundColor: '#DCDCDC',
        height: '100%',
        position: 'absolute',
        left: 105,
        top: 0,
        zIndex: -1,
    },
    cardTimeLine: {
        flexDirection: 'row',
        alignItems: 'center',
        // backgroundColor: '#fff',
        marginTop: 10,
    },
    cardTimeLineDay: {
        width: 80,
        textAlign: 'center',
        fontSize: 14,
        color: '#999',
    },
    cardTimeLineDayCur: {
        width: 80,
        textAlign: 'center',
        fontSize: 14,
        color: '#666',
    },
    cardTimeLineImgBoxCur: {
        backgroundColor: '#fff',
        height: 30,
        width: 30,
        marginHorizontal: 10,
        alignItems: 'center',
        justifyContent: 'center',
    },
    cardTimeLineImgCur: {
        width: 24,
        height: 24,
    },
    cardTimeLineImgBox: {
        backgroundColor: '#fff',
        height: 20,
        width: 30,
        marginHorizontal: 10,
        alignItems: 'center',
        justifyContent: 'center',
    },
    cardTimeLineImg: {
        width: 10,
        height: 10,
    },
    cardTimeLineRightArrow: {
        width: 10,
        marginRight: -3,
    },
    cardTimeLineRight: {
        flex: 1,
        backgroundColor: '#f2f2f2',
        padding: 10,
        borderRadius: 5,
        marginLeft: 7,
    },
    cardTimeLineRightText: {
        color: '#999',
        fontSize: 14,
    },
    cardTimeLineRightCur: {
        flex: 1,
        backgroundColor: DominantColor,
        padding: 10,
        borderRadius: 5,
    },
    cardTimeLineRightTextCur: {
        color: '#fff',
        fontSize: 14,
    },


    // 底部的按钮
    bottomBtnBox: {
        paddingVertical: 10,
        paddingHorizontal: 15,
        backgroundColor: '#fff',
    },
    bottomBtn: {
        backgroundColor: DominantColor,
        borderRadius: 5,
    },
    bottomBtnTitle: {},

    webContainer: {
        height: SCREEN_WIDTH * 2/3,
        width: SCREEN_WIDTH,
    },
});